﻿using System.Windows;
using System.Windows.Input;
using FastColoredTextBoxNS;
using System.Text.RegularExpressions;


namespace MPE
{
    public partial class findWindow : Window
    {
        public findWindow() { InitializeComponent(); tbFind.Focus(); }
        Place startPlace;
        FastColoredTextBox tb { get => DataHelper.field; }
        bool firstSearch = true;
        void BtFindNext_Click(object sender, RoutedEventArgs e) => FindNext(tbFind.Text);
        public void setTextInFindTB(string text) { tbFind.Text = text; }
        void FindNext(string pattern)
        {
            RegexOptions opt = cbMatchCase.IsChecked == true ? RegexOptions.None : RegexOptions.IgnoreCase;
            if (!cbRegex.IsChecked == true)
                pattern = Regex.Escape(pattern);
            if (cbWholeWord.IsChecked == true)
                pattern = "\\b" + pattern + "\\b";

            Range range = tb.Selection.Clone();
            range.Normalize();

            if (firstSearch)
            {
                startPlace = range.Start;
                firstSearch = false;
            }

            range.Start = range.End;
            if (range.Start >= startPlace)
                range.End = new Place(tb.GetLineLength(tb.LinesCount - 1), tb.LinesCount - 1);
            else
            {
                range.End = startPlace;
                firstSearch = true;
            }

            foreach (var r in range.GetRangesByLines(pattern, opt))
            {
                tb.Selection = r;
                tb.DoSelectionVisible();
                tb.Invalidate();
                return;
            }

            if (range.Start >= startPlace && startPlace > Place.Empty)
            {
                tb.Selection.Start = new Place(0, 0);
                FindNext(pattern);
                return;
            }
            tb.Selection.Start = new Place(0, 0);
            tb.Selection.End = new Place(0, 0);
        }
        void TbFind_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { FindNext(tbFind.Text); e.Handled = true; return; } }
        void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) => DragMove();
    }
}